import java.io.*;
import java.net.*;

public class Handler implements Runnable{

	/**
	 *  Socket per la connessione
	 */
	private Socket socket;
	/**
	 *  Messaggio univoco per identificare il programma
	 */	
	private String header;
	/**
	 *  Thread this
	 */
	private Thread t;
	/**
	 *  File writer per i log
	 */
	private FileWriter fw;
	
	/**
	 *  Costruttore della classe handler
	 */
	public Handler(Socket _socket, String _header, FileWriter _fw) {
		socket=_socket;
		header=_header;
		fw = _fw;
		t= new Thread(this);
	}
	/**
	 *  Metodo principale per la gestione del client
	 */
	public void run() {
		try{
			BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); // lettura di dati che vengono dal client
			
			PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream() ) ) , true);
			String msg;
			
			do // loop fino a quando non riceve "end"
			{
				msg = in.readLine();
				try {
					if(msg.equalsIgnoreCase("end")) out.println(header+"Programma terminato");
					else out.println(header+"Tu mi hai detto: "+msg);
				}
				catch(NullPointerException e) { System.out.println("ERROR: Connection from remote host has been closed"); }
			}
			while(!msg.equalsIgnoreCase("end"));	
			
			
			// Chiudi gli stream
			socket.close();
			out.close();
			in.close();
			fw.write("[+] Connection closed");
		}
		catch(IOException e) {
			System.out.println("ERRORE IO: "+ e);
		}
		System.out.println("[+] Connection closed");	
	}
	
	/**
	 *  Metodo per avviare il thread
	 */
	public void start(){
		t.start();
	}
	
}//class
